<?php

namespace App\Http\Middleware;

use App\Utils\ApiResponse;
use Closure;

class EncryptRequestMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    /**
     * 超时时间
     * @var float|int
     */
    private $apiTimeOut = 3600 * 24;

    public function handle($request, Closure $next)
    {
        // 获取当前请求的路由信息
        $route = $request->route();
        $currentRouteName = $route->getName();

        // 定义你想要去除的接口路由名称，进行判断
        $excludedRoutes = [
            'hello',
            'auth.search',
            'auth.set'
            //'wechat.oss', //路由名称
            //'wechat.payment.notify',
        ];

        // 如果当前路由在去除列表中，直接放行
        if (in_array($currentRouteName, $excludedRoutes)) {
            return $next($request);
        }

        // 获取加密的参数
        $encryptedData = $request->all();
        if (!isset($encryptedData['encry_content']) || empty($encryptedData['encry_content'])) {
            ApiResponse::fail("数据验证失败");
        }
        $encryptedData = $encryptedData['encry_content'];
        $key = '111111'; // 一个随机的 32 字节密钥
        $iv = '222222'; // 一个随机的 16 字节初始向量
        $method = 'AES-256-CBC'; // 使用 AES-256-CBC 加密算法
        $decryptedData = openssl_decrypt(base64_decode($encryptedData), $method, $key, OPENSSL_RAW_DATA, $iv); // 执行解密操作

        if ($decryptedData === false) {
            ApiResponse::fail("数据验证失败");
        }

        // 解密后的数据
        $decryptedDataObj = json_decode($decryptedData);

        // 验证请求时间
        if (!isset($decryptedDataObj->timestamp) || time() - $decryptedDataObj->timestamp > $this->apiTimeOut) {
            ApiResponse::fail("请求时间异常");
        }
        unset($decryptedDataObj->timestamp);
        // 将解密后的参数设置回请求对象
        $request->merge(['decrypted_data' => $decryptedDataObj]);

        return $next($request);
    }
}
